package com.ruoyi.netty.storage;

import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

/**
 * 数据查询服务
 */
@Service
@Slf4j
public class DataQueryService {

    //@Autowired
    private InfluxDBService influxDBService;
    
    /**
     * 按时间范围和设备ID查询数据
     * 
     * @param measurement 测量名称
     * @param deviceId 设备ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param aggregateFunction 聚合函数 (mean, max, min, sum, count)
     * @param interval 时间间隔 (如 1m, 5m, 1h)
     * @return 查询结果
     */
    public QueryResult queryByTimeRangeAndDevice(
            String measurement,
            String deviceId,
            Instant startTime,
            Instant endTime,
            String aggregateFunction,
            String interval) {
        
        // 构建InfluxQL查询
        String query = "SELECT " + aggregateFunction + "(value) FROM \"" + measurement + "\" " +
                "WHERE deviceId = '" + deviceId + "' " +
                "AND time >= '" + startTime + "' " +
                "AND time <= '" + endTime + "' " +
                "GROUP BY time(" + interval + ") fill(null)";
        
        log.debug("Executing query: {}", query);
        return influxDBService.queryWithFlux(query);
    }
    
    /**
     * 查询最近N小时的设备数据
     * 
     * @param measurement 测量名称
     * @param deviceId 设备ID
     * @param hours 小时数
     * @return 查询结果
     */
    public QueryResult queryRecentData(String measurement, String deviceId, int hours) {
        Instant endTime = Instant.now();
        Instant startTime = endTime.minus(hours, ChronoUnit.HOURS);
        
        return queryByTimeRangeAndDevice(
                measurement,
                deviceId,
                startTime,
                endTime,
                "mean",
                "5m");
    }
    
    /**
     * 查询设备报警数据
     * 
     * @param deviceId 设备ID
     * @param days 天数
     * @return 查询结果
     */
    public QueryResult queryAlarms(String deviceId, int days) {
        Instant endTime = Instant.now();
        Instant startTime = endTime.minus(days, ChronoUnit.DAYS);
        
        String query = "SELECT * FROM \"alarms\" " +
                "WHERE deviceId = '" + deviceId + "' " +
                "AND time >= '" + startTime + "' " +
                "AND time <= '" + endTime + "' " +
                "ORDER BY time DESC";
        
        return influxDBService.queryWithFlux(query);
    }
} 